package com.giveu.signature.module.template.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.giveu.common.fastdfs.service.FastdfsClientService;
import com.giveu.common.page.PageBuilder;
import com.giveu.common.page.PageInfoBT;
import com.giveu.common.page.QueryMap;
import com.giveu.signature.common.constants.FileSuffix;
import com.giveu.signature.common.constants.TempType;
import com.giveu.signature.common.service.BaseController;
import com.giveu.signature.common.util.SignFileUtil;
import com.giveu.signature.config.FeignProperties;
import com.giveu.signature.conts.GenModel;
import com.giveu.signature.module.template.model.SignTemplateHtml;
import com.giveu.signature.module.template.model.SignatureConfig;
import com.giveu.signature.module.template.service.SignTemplateHtmlService;
import com.giveu.signature.module.template.service.SignTemplateParamService;
import com.giveu.signature.module.template.service.SignatureConfigService;

@Controller
@RequestMapping("/templateHtml")
public class SignTemplateHtmlController extends BaseController{

	private static final Logger log = LoggerFactory.getLogger(SignTemplateHtmlController.class);

	private static final String PREFIX = "module/template/html/";

	@Autowired
	SignTemplateHtmlService signTemplateHtmlService;
	@Autowired
	FastdfsClientService fastdfsClientService;
	@Autowired
	FeignProperties feignProperties;
	@Autowired
	SignTemplateParamService signTemplateParamService;
	@Autowired
	SignatureConfigService signatureConfigService;

	@RequestMapping("")
	private String index(Model model) {
		return PREFIX + "index";
	}

	@RequestMapping("/view/{id}")
	private String view(@PathVariable("id") Long id,Model model) {
		SignTemplateHtml entity = signTemplateHtmlService.get(id);
		model.addAttribute("entity", entity==null?new SignTemplateHtml():entity);
		model.addAttribute("tempTypes", TempType.values());
		model.addAttribute("paramMaps", signTemplateParamService.paramMaps());
		model.addAttribute("genModels", GenModel.values());
		return PREFIX + "view";
	}
	
	@RequestMapping("/edit/{id}")
	private String edit(@PathVariable("id") Long id,Model model) {
		if(id!=0){
			SignTemplateHtml entity = signTemplateHtmlService.get(id);
			model.addAttribute("entity", entity==null?new SignTemplateHtml():entity);
			model.addAttribute("signJson", JSON.toJSONString(entity.getSignList()));
		}else{
			model.addAttribute("entity", new SignTemplateHtml());
		}
		model.addAttribute("tempTypes", TempType.values());
		model.addAttribute("genModels", GenModel.values());
		model.addAttribute("paramMaps", signTemplateParamService.paramMaps());
		
		return PREFIX + "edit";
	}
	
	@RequestMapping("/modify/{id}")
	private String modify(@PathVariable("id") Long id,Model model) {
		SignTemplateHtml entity = signTemplateHtmlService.get(id);
		if(entity!=null){
			entity.setId(null);
			entity.setModify(true);
			entity.setTempVersion(entity.getTempVersion()+1);
		}
		model.addAttribute("entity", entity==null?new SignTemplateHtml():entity);
		model.addAttribute("tempTypes", TempType.values());
		model.addAttribute("paramMaps", signTemplateParamService.paramMaps());
		model.addAttribute("genModels", GenModel.values());
		model.addAttribute("signJson", JSON.toJSONString(entity.getSignList()));
		return PREFIX + "edit";
	}
	

	@RequestMapping("/list")
	@ResponseBody
	private Object list(SignTemplateHtml entity) {
		QueryMap<SignTemplateHtml> queryMap = PageBuilder.buildQueryMap();
		queryMap.setEntity(entity);
		PageInfo<SignTemplateHtml> pageInfo = signTemplateHtmlService.listByPage(queryMap);
		return new PageInfoBT<>(pageInfo);
	}

	@RequestMapping("/save")
	@ResponseBody
	private Object save(@RequestBody SignTemplateHtml entity) {
		signTemplateHtmlService.save(entity);
		return SUCCESS_TIP;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	private Object delete(SignTemplateHtml entity) {
		signTemplateHtmlService.delete(entity);
		return SUCCESS_TIP;
	}
	
	
	@RequestMapping("/submit")
	@ResponseBody
	private Object submit(@RequestBody SignTemplateHtml entity) {
		entity.setTempStatus(1);
		File file = null;
		try {
			file = SignFileUtil.genHtml(entity.getHtmlText());
			if (GenModel.HTML.getCode().equals(entity.getGenModel())) {
				entity.setFastUrl(fastdfsClientService.fileUpload(file));
			}
			signTemplateHtmlService.save(entity);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally {
			if(file!=null){
				file.deleteOnExit();
			}
		}
		return SUCCESS_TIP;
	}
	

	
	@RequestMapping("uploadPage")
	private String uploadPage(Model model) {
		return PREFIX + "upload";
	}
	
	@SuppressWarnings("serial")
	@RequestMapping("/uploadFile")
	@ResponseBody
	private Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
		Map<String, Object> resultMsg = new HashMap<String, Object>(){{put("success", false);}};
		if (file == null || file.isEmpty()) {
			resultMsg.put("messgae", "上传文件为空");
			return resultMsg;
		}
        String suffix = SignFileUtil.getSuffix(file);
		if(!FileSuffix.checkSuffix(suffix)){
			resultMsg.put("messgae", "文件类型上传有误");
			return resultMsg;
		}
		File fl = null;
		try {
			fl = SignFileUtil.genTemporaryFile(file);
			resultMsg.put("content",SignFileUtil.readContent(fl));
			resultMsg.put("success", true);
		} catch (Exception e) {
			resultMsg.put("messgae", e.getMessage());
		}finally {
			if(fl!=null){
				fl.deleteOnExit();
			}
		}
		return resultMsg;
	}
	
	@SuppressWarnings("serial")
	@RequestMapping("/uploadFastdfs")
	@ResponseBody
	private Map<String, Object> uploadFastdfs(@RequestParam("file") MultipartFile file) {
		Map<String, Object> resultMsg = new HashMap<String, Object>(){{put("success", false);}};
		if (file == null || file.isEmpty()) {
			resultMsg.put("messgae", "上传文件为空");
			return resultMsg;
		}
        String suffix = SignFileUtil.getSuffix(file);
		if(!FileSuffix.checkSuffix(suffix)){
			resultMsg.put("messgae", "文件类型上传有误");
			return resultMsg;
		}
		try {
			String content = fastdfsClientService.fileUpload(file);
			resultMsg.put("content",content);
			resultMsg.put("fastPath",feignProperties.getFastdfsUrl()+content);
			resultMsg.put("success", true);
		} catch (Exception e) {
			resultMsg.put("messgae", e.getMessage());
		}finally {
		}
		return resultMsg;
	}
	
	
	@RequestMapping("tryHtml")
	private String tryHtml(Model model) {
		return PREFIX + "tryHtml";
	}
}
